from tortoise import Model, fields
from ph_utils.date import timestamp


class BaseModel(Model):
    """所有的表的基类"""

    id = fields.IntField(pk=True)
    """主键, 自增长id"""

    createAt = fields.IntField(source_field="create_at", null=True)
    """创建日期，时间戳(秒)"""

    def setCreateAt(self, time=None):
        self.createAt = timestamp() if time is None else time

    def update(self, data: dict):
        """更新字典中的非空数据到对象

        Args:
            data (dict): 数据源
        """
        if data is not None:
            for k in data:
                if data[k] is not None and hasattr(self, k):
                    v = data[k]
                    if isinstance(v, list):
                        setattr(self, k, ",".join(v))
                    else:
                        setattr(self, k, v)

    class Meta:
        abstract = True  # 抽象模型，用于继承


class KeyApp(BaseModel):
    """ 做签名校验的app列表 """

    app_id = fields.CharField(20)

    app_secret = fields.CharField(50)

    name = fields.CharField(50, null=True)
    """ 应用名称 """

    status = fields.IntField(default=1)
    """ 是否有效,1-有效,0-无效 """

    class Meta:
        table = "{{= d.name.toLowerCase().replace('-', '_') }}_key_app"
        table_description = "做签名校验的app列表"


class IpWhitelist(BaseModel):
    """ 应用 IP 白名单 """

    app_id = fields.CharField(20)
    ip = fields.CharField(20)

    class Meta:
        table = "{{= d.name.toLowerCase().replace('-', '_') }}_ip_whitelist"
        table_description = "IP白名单"
